//index.js
//获取应用实例
const app = getApp();
const Util = require('../../utils/util.js');
const Layer = require('../layer/layer.js');
import Poster from '../../miniprogram_dist/poster/poster';
Page({
  data: {
    addPhoto: true,
    focus: false,

    token: '',
    cate_id: '',
    cateData: {},

    imagesData: [],
    imagesBigData: [],
    imagesNumber: 0,
    addRole: false,
    userNumber: 0,
    userList: {},

    animationPop: {},
    popLogin: {},

    refresh: false,
    userInfo: []
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function (e) {
    var that = this;
    var cateId = e.cate_id;
    if (e.scene) {
      cateId = e.scene;
    }
    that.setData({
      cate_id: cateId
    });
    wx.getStorage({
      key: 'token',
      success: function (res) {
        if (res.data) {
          that.setData({
            token: res.data
          });
          Util.showLoading();
          that.getPhotoData();
        }
      }, fail: function () {
        that.checkUser(-1, function (isauth) {
          console.info(isauth);
          if (isauth) {
            that.setData({
              addPhoto: false,
              focus: true
            })
          } else {
            mytoast.toast();
            Util.showMsgDialog("请先授权再使用");
          }
        })
      }
    })
  },
  onShow: function (e) {
    var that = this;
    var token = that.data.token;
    if (token && that.data.refresh) {
      console.info(1);
      that.getPhotoData();
    }
    app.aData.show = true;
  },
  checkUser: function (action, cb) {
    var that = this;
    wx.getStorage({
      key: 'token',
      success: function (res) {
        if (res.data) {
          cb(true);
        }
      },
      fail: function () {
        Util.checkAuth(function (res) {
          if (!res.authSetting['scope.userInfo']) {
            //未授权用户
            that.showLogin();
          } else {
            app.getUserInfo(true, function (userInfo) {
              if (typeof cb == "function") {
                cb(true);
              }
              //that.getData();
            });
          }
        });
      }
    })
  },
  onHide() {
    app.aData.show = false;
  },
  getPhotoData: function () {
    var that = this;
    var token = that.data.token;
    var cate_id = that.data.cate_id;
    console.info(that.data);
    if(cate_id){
      Util.getPhotoData({
        "token": token,
        "cate_id": cate_id
      }, function (re) {
        console.info(re);
        that.setData({
          imagesData: re.data,
          imagesNumber: re.imagesNumber,
          imagesBigData: re.bigImages,
          cateData: re.cate,
          addRole: re.addRole,
          userNumber: re.userNumber,
          userList: re.user_list,
          userInfo: re.user
        });
        wx.hideLoading();
      }, function (err) {
        Util.showMsgDialog("操作失败");
      })
    }
  },
  setting: function () {
    var that = this;
    var data = that.data.cateData;
    that.data.refresh = true;
    wx.navigateTo({
      url: 'setting?cateName=' + data.name + '&cateId=' + data.id
    })
  },
  addImages: function () {
    var that = this;
    that.data.refresh = false;
    var token = that.data.token;
    var cate_id = that.data.cate_id;
    var userInfo = that.data.userInfo;
    var imagesData = that.data.imagesData;
    var imagesBigData = that.data.imagesBigData;
    console.info(imagesBigData);
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        var num = tempFilePaths.length;
        var imagesNumber = that.data.imagesNumber;
        that.setData({
          imagesNumber: parseInt(imagesNumber) + parseInt(num)
        })
        for (var i = 0; i < num; i++) {
          Util.showLoading('上传中');
          console.info(token);
          wx.uploadFile({
            url: 'https://wx.himayi.cn/Home/Index/add_images', //仅为示例，非真实的接口地址
            filePath: tempFilePaths[i],
            name: 'thumb',
            formData: {
              'token': token,
              'cate_id': cate_id
            },
            success: function (ret) {
              var r = JSON.parse(ret.data);
              var json = new Array();
              var arr = new Object();
              var img = new Array();
              arr['id'] = 520;
              arr['thumb'] = r.data;
              arr['nickname'] = userInfo['nickname'];
              arr['is_zan'] = 0;
              arr['user_img'] = userInfo['thumb'];
              json[0] = arr;
              img[0] = r.big_img;
              for (var i = 0; i < imagesData.length;i++){
                json[i+1] = imagesData[i];
                img[i + 1] = imagesBigData[i];
              }
              console.info(img);
              that.setData({
                imagesData: json,
                imagesBigData: img
              });
              wx.hideLoading();
            }
          })
        }
      }
    })
  },
  memberList: function () {
    var that = this;
    that.data.refresh = false;
    var cate_id = that.data.cate_id;
    wx.navigateTo({
      url: 'member?cate_id=' + cate_id
    })
  },
  setZan: function (e) {
    var that = this;
    var gid = e.currentTarget.dataset.id;
    var idx = e.currentTarget.dataset.idx;
    var imagesData = that.data.imagesData;
    var token = that.data.token;
    Util.setImagesZan({
      "token": token,
      "gid": gid
    }, function (re) { })
    var num = parseInt(imagesData[idx]['zan_number']);
    if (imagesData[idx]['is_zan'] == 1) {
      imagesData[idx]['zan_number'] = num - 1;
      imagesData[idx]['is_zan'] = 0;
    } else {
      imagesData[idx]['zan_number'] = num + 1;
      imagesData[idx]['is_zan'] = 1;
    }
    that.setData({
      imagesData: imagesData
    });
  },
  bigImages: function (e) {
    var img = e.currentTarget.dataset.img;
    var imagesData = this.data.imagesBigData;
    wx.previewImage({
      current: img,
      urls: imagesData
    })
  },
  sharePhoto: function () {
    var that = this;
    that.data.refresh = false;
    var cate_id = that.data.cate_id;
    Layer.layer.bottomShare('分享相册', '取消', that, function () {
      Layer.layer.close(that);
    }, function () {
      Util.showLoading();
      wx.navigateTo({
        url: '../main/share?cate_id=' + cate_id
      })
    });
  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },
  showLogin: function () {
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: "ease",
      delay: 0
    })
    this.animation = animation
    animation.scale(0).step()

    this.setData({
      popLogin: animation.export(),
      popLoginStatus: true
    })

    setTimeout(function () {
      animation.scale(1.0).step()
      this.setData({
        popLogin: animation
      })
    }.bind(this), 100)
  },
  showPop: function (status) {
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: "ease",
      delay: 0
    })
    this.animation = animation
    animation.scale(0).step()

    this.setData({
      animationPop: animation.export()
    })
    if (status == 1) {
      this.setData(
        {
          showPopStatus: true
        }
      );
    }
    setTimeout(function () {
      animation.scale(1.0).step()
      this.setData({
        animationPop: animation
      })
      if (status == 0) {
        this.setData(
          {
            showPopStatus: false,
          }
        );
      }
    }.bind(this), 300)
  },
  onGotUserInfo: function (e) {
    var that = this;
    if (e.detail.errMsg == 'getUserInfo:ok') {
      app.getUserInfo(true, function (userInfo) {
        that.setData({
          token: userInfo
        });
        that.getPhotoData();
      });
    }
    that.setData({
      popLoginStatus: false
    })
  },
  onShareAppMessage: function (res) {
    var cate_id = this.data.cate_id;
    var imagesData = this.data.imagesData;
    console.info(imagesData[0].thumb);
    return {
      title: 'Hi,推荐你用用这个小程序',
      path: '/pages/main/content?cate_id=' + cate_id,
      imageUrl: imagesData[0].thumb
    }
  }
})